import { Controller, Get, Post, Body, Inject, Query, HttpCode } from '@nestjs/common';
import { SysService } from './sys.service';
import { UserService } from '../user/user.service';
import { AllowNoToken } from '../common/decorators/token.decorator';
import { CreateUserDto } from '../user/dto/create-user.dto';
import { LoginDto, LoginUserDto } from './dto/login-user.dto';
import { ForgotUserDto } from './dto/forgot-user.dto';
import { ApiBody, ApiOperation } from '@nestjs/swagger';
import { ConfigService } from '../common/config/config.service';
import { createMath } from '../common/utils/captcha';
import { GenerateUUID } from '../common/utils';
import { RedisService } from '../common/redis/redis.service';
import { RedisKeyPrefix } from '../common/enums/redis-key.enum';
import { ResultData } from '../common/utils/result';
import { User, UserDto } from '../user/user.decorator';

@Controller('sys')
export class SysController {
  @Inject(UserService)
  private userService: UserService;
  constructor(
    private readonly sysService: SysService,
    private readonly configService: ConfigService,
    private readonly redisService: RedisService,
  ) {}

  // 用户注册
  @Post('registry')
  @AllowNoToken()
  registry(@Body() createUserDto: CreateUserDto) {
    return this.userService.registry(createUserDto);
  }

  // 用户登录 老版本
  // @Post('login')
  // login(@Body() loginUserDto: LoginUserDto) {
  //   return this.userService.login(loginUserDto);
  // }

  // todoAdmin新版登录
  @ApiOperation({
    summary: '用户登录',
  })
  @ApiBody({
    type: LoginDto,
    required: true,
  })
  @Post('/login')
  @HttpCode(200)
  login(@Body() user: LoginDto, @ClientInfo() clientInfo: ClientInfoDto) {
    return this.userService.login(user, clientInfo);
  }

  // 获取验证码图片
  @ApiOperation({
    summary: '获取验证码图片',
  })
  @Get('/captchaImage')
  async captchaImage() {
    //是否开启验证码
    const enable = await this.configService.getConfigValue(
      'sys.account.captchaEnabled',
    );
    // true
    const captchaEnabled: boolean = enable === 'true';
    const data = {
      captchaEnabled,
      img: '',
      uuid: '',
    };
    try {
      if (captchaEnabled) {
        const captchaInfo = createMath();
        data.img = captchaInfo.data;
        data.uuid = GenerateUUID();
        await this.redisService.set(
          RedisKeyPrefix.CAPTCHA_CODE_KEY + data.uuid,
          captchaInfo.text.toLowerCase(),
          1000 * 60 * 5,
        );
      }
      return ResultData.ok(data, '操作成功');
    } catch (err) {
      return ResultData.fail(500, '生成验证码错误，请重试');
    }
  }

  @ApiOperation({ summary: '账号自助-是否开启用户注册功能' })
  @Get('/registerUser')
  async registerUser() {
    // 是否开启验证码
    const enable = await this.configService.getConfigValue(
      'sys.account.registerUser',
    );
    return ResultData.ok(enable === 'true');
  }

  @ApiOperation({
    summary: '用户信息',
  })
  @Get('/getInfo')
  async getInfo(@User() user: UserDto) {
    return {
      msg: '操作成功',
      code: 200,
      permissions: user.permissions,
      roles: user.roles,
      user: user.user,
    };
  }

  // 发送注册邮箱验证码
  @Get('sendEmailForRegistry')
  @AllowNoToken()
  sendEmailForRegistry(@Query() dto: { email: string }) {
    return this.sysService.sendMailForRegistry(dto.email, '注册验证码');
  }

  // 找回密码
  @Post('forgot')
  @AllowNoToken()
  forgot(@Body() forgotUserDto: ForgotUserDto) {
    return this.userService.updatePassword(forgotUserDto);
  }
  // 发送找回密码邮箱验证码
  @Get('sendEmailForGorgot')
  @AllowNoToken()
  sendEmailForGorgot(@Query() dto: { email: string }) {
    return this.sysService.sendEmailForGorgot(dto.email);
  }

  //
  // // 上传文件
  // @Post('upload')
  // @UseInterceptors(FileInterceptor('file'))
  // uploadFile(
  //   @UploadedFile() file: Express.Multer.File,
  //   @Body() data: { type: string },
  // ) {
  //   return this.sysService.upload(file, data.type);
  // }
}
